import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter_module/beans/DeviceTypeList.dart';
import 'package:flutter_module/beans/configResult.dart';
import 'package:flutter_module/beans/conmmonResult.dart';
import 'package:flutter_module/http/api_service.dart';
import 'package:flutter_module/http/dio_manager.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:smartconfig/smartconfig.dart';

import '../DemoLocalizations.dart';

class Connwifi extends StatefulWidget {
  @override
  _ConnwifiState createState() => _ConnwifiState();
}

class _ConnwifiState extends State<Connwifi> {
  String _bssid = '';
  String _key = '';
  String _keys = '';
  String _ssid = '';
  String _msg = 'waiting';
  bool issuccse = false;
  TextEditingController _phonecontroller = new TextEditingController();
  Timer _ct;
  int _tmp = 0;
  List<Records> mrecords;
  List<PopupMenuItem<String>> popupMenu = new List();
  String deviceType;

  //本地绑定的次数
  int _localTime = 0;

  bindAtBgWith24C16(String lanip) async {
    //SharedPreferences sp = await SharedPreferences.getInstance();
    String uuid = "";
    ApiService().appPair((Response response) {
      if (response != null) {
        ConmmonResult conmmonResult = ConmmonResult.fromJson(response.data);
        if (conmmonResult.success) {
          print(conmmonResult.code);
          Navigator.pop(context);
        } else {
          if (_tmp < 11) {
            Future.delayed(Duration(seconds: 2), () {
              bindAtBgWith24C16(lanip);
//                print('延时2s执行');
            });
          }
          if (_tmp > 2) {
            showToast(conmmonResult.message);
          }

//            Navigator.pop(context);
          print(conmmonResult.code);
        }
      }
    }, lanip, uuid, deviceType);
  }

  void getdtl() {
    ApiService().getDeviceTypeList((Response response) {
      if (response != null) {
        ConmmonResult conmmonResult = ConmmonResult.fromJson(response.data);
        if (conmmonResult.success) {
          DeviceTypeList conmmonResult = DeviceTypeList.fromJson(response.data);
          setState(() {
            mrecords = conmmonResult.result.records;
            popupMenu = new List();
            for (int i = 0, length = mrecords.length; i < length; i++) {
              popupMenu.add(PopupMenuItem<String>(
                child: Text(mrecords.elementAt(i).type.toString()),
                value: mrecords.elementAt(i).typekey.toString(),
              ));
            }
          });
          _initWifi();
        } else {
          showToast(conmmonResult.message);
          setState(() {
            _msg = '请确认您手机已经连接到可用Wi-Fi，连接好后点击下方重试按钮。';
          });
        }
      }
    });
  }

  void _tgo() {
    _ct = Timer.periodic(new Duration(seconds: 5), (timer) {
      if (_tmp < 10) {
        _tmp++;
        //_querySetNetWork();
      } else {
        setState(() {
          _msg = DemoLocalizations.of(context).BindingFailedPleaseCheck;
        });
        if (_ct != null) _ct.cancel();
      }
    });
  }

  _ConnwifiState() {
//      getdtl();
    _initWifi();
  }

  @override
  void dispose() {
    if (_ct != null) _ct.cancel();
    super.dispose();
  }

  _initWifi() async {
    print("_initWifi");

    String bssid = await (Connectivity().getWifiBSSID());
    String ip = await (Connectivity().getWifiIP());
    String ssid = await (Connectivity().getWifiName());
//    print(bssid + "||" + ip + "||" + ssid);
    _bssid = bssid;
    _ssid = ssid;
    if (_ssid == null ||
        _bssid == null ||
        _ssid.length < 1 ||
        _bssid.length < 1) {
      setState(() {
        _msg = DemoLocalizations.of(context).confirmWiFi;
      });
    } else {
      setState(() {
        _msg = DemoLocalizations.of(context).checkleft +
            _ssid +
            DemoLocalizations.of(context).checkright;
      });
    }
  }

  _smartConfig(String ssid, String bssid, String password) async {
//    print("start Config ...");
//    print(ssid);
//    print(bssid);
//    print(password);
    _tmp = 0;
    Smartconfig.start(ssid, bssid, password).then((onValue) {
      if (onValue == null) {
        return;
      }
      String lanip = onValue.toString().substring(
          onValue.toString().indexOf(" ") + 1, onValue.toString().length - 1);
//      print("laniplaniplanip");
//      print(lanip);
      if (lanip.isNotEmpty) {
        Future.delayed(Duration(seconds: 4), () {
          bindAt24C16(lanip);
//            print('延时4s执行');
        });
        showToast(DemoLocalizations.of(context).connectedInternet);
      } else {
        showToast(DemoLocalizations.of(context).BindingFailedPleaseCheck);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
//    _msg = DemoLocalizations.of(context).Initializing;
//    print("_initWifi2");
//    _initWifi();
    final size = MediaQuery.of(context).size;
    final width = size.width;
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(
          color: Colors.white, //修改颜色
        ),
        title: Text(
          DemoLocalizations.of(context).addDevice,
          // style: TextStyle(color: Color(0xff000000)),
        ),
        // backgroundColor: Color(0xffD7D8DA),
        centerTitle: true,
      ),
      backgroundColor: Color.fromARGB(255, 26, 16 * 8 + 4, 13 * 16 + 10),
      // backgroundColor: Color(0xffFFFFFF),

      body: Column(
        children: <Widget>[
          Expanded(
            child: Container(
//              color: Colors.red,
              child: (_msg == null || _msg.length < 1)
                  //? Image.asset('img/sm.gif')
                  ? Image.asset('assets/gifs/sm.gif')
                  : Center(
                      child: Container(
                        padding: EdgeInsets.all(50),
                        child: Text(
                          _msg,
                          style:
                              // TextStyle(color: Color(C), fontSize: 16),
                              TextStyle(color: Color(0xffD7D8DA), fontSize: 16),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
            ),
          ),
          (_msg == null || _msg.length < 1)
              ? Container()
              : Container(
                  width: double.infinity,
                  height: 180,
                  child: Center(
                    child: (_ssid == null ||
                            _bssid == null ||
                            _ssid.length < 1 ||
                            _bssid.length < 1)
                        ? MaterialButton(
                            color: Colors.white,
                            height: 45,
                            minWidth: 220,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                            onPressed: () {
                              _initWifi();
//                              getdtl();
                            },
                            child: Text(
                              DemoLocalizations.of(context).retry,
                              style: TextStyle(
                                  color: Colors.blueAccent, fontSize: 20),
                            ),
                          )
                        : (_msg != null &&
                                _msg ==
                                    DemoLocalizations.of(context)
                                        .Distributionnetworksuccess)
                            ? Container(
                                child: MaterialButton(
                                  color: Colors.white,
                                  height: 45,
                                  minWidth: width - 100,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(25),
                                  ),
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                  child: Text(
                                    DemoLocalizations.of(context).returnT,
                                    style: TextStyle(
                                        color: Colors.blueAccent, fontSize: 20),
                                  ),
                                ),
                              )
                            : Container(
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: <Widget>[
                                    // Center(
                                    //   child: PopupMenuButton(
                                    //     child: Text(deviceType!=null?deviceType:"请点击选择机器类型"),
                                    //     tooltip: "长按提示必选项",
                                    //     initialValue: "hot",
                                    //     padding: EdgeInsets.all(0.0),
                                    //     itemBuilder: (BuildContext context) {
                                    //       return popupMenu;
                                    //     },
                                    //     onSelected: (String action) {
                                    //       for (int i = 0, length = mrecords.length; i < length; i++) {
                                    //         if(action==mrecords.elementAt(i).typekey.toString()){
                                    //           deviceType = mrecords.elementAt(i).typekey.toString();
                                    //           setState(() {
                                    //           });
                                    //         }
                                    //       }
                                    //     },
                                    //     onCanceled: () {
                                    //       print("onCanceled");
                                    //     },
                                    //   ),
                                    // ),
                                    Container(
                                        width: width - 100,
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(30.0)),
                                          boxShadow: <BoxShadow>[
                                            new BoxShadow(
                                              color: Colors.black45,
                                              blurRadius: 5.0,
                                              offset: Offset(1.0, 3.0),
                                            ),
                                          ],
                                        ),
                                        child: Container(
                                          padding: EdgeInsets.only(
                                              left: 25, right: 25),
                                          child: TextField(
                                            controller: _phonecontroller,
                                            keyboardType:
                                                TextInputType.visiblePassword,
                                            decoration: new InputDecoration(
                                                hintText: DemoLocalizations.of(
                                                        context)
                                                    .enterWiFipassword,
                                                border: InputBorder.none),
                                          ),
                                        )),
                                    MaterialButton(
                                      color: Color(0xff410ADF),
                                      height: 45,
                                      minWidth: width - 100,
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(25),
                                      ),
                                      onPressed: () {
                                        setState(() {
//                                          if (_phonecontroller.text == null ||
//                                              _phonecontroller.text.length <
//                                                  8) {
//                                            _msg = '请先输入8位及以上Wi-Fi密码！';
//                                            showToast(_msg);
//                                          } else {
                                          _msg = '';
                                          _tgo();
                                          _smartConfig(_ssid, _bssid,
                                              _phonecontroller.text);
//                                          }
                                        });
                                      },
                                      child: Text(
                                        DemoLocalizations.of(context)
                                            .distributionNetwork,
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 20),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                  ),
                ),
        ],
      ),
    );
  }

  Future<void> bindAt24C16(String lanip) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String uuid = sp.getString("uuid");
    if (uuid == null || uuid.isEmpty) {
//    showToast("用户信息缺失请重新登陆!");
    } else {
      print(uuid);
      String url = "http://" + lanip + ":8081/bind?uuid=" + uuid;
      //+"&deviceType="+deviceType
      print(url);
      myappPair((Response response) {
        if (response != null) {
          configResult conmmonResult;
          try {
            conmmonResult = configResult.fromJson(json.decode(response.data));
          } catch (e) {
            _localTime++;
            if (_localTime > 5) {
              showToast(DemoLocalizations.of(context).BindingFailedPleaseCheck);
            }
//          print('json解析出错');
            Future.delayed(Duration(seconds: 1), () {
              bindAt24C16(lanip);
            });
            return;
          }

          if (conmmonResult.success) {
            setState(() {
              _msg =
                  DemoLocalizations.of(context).DistributionNetworkSuccessLong;
              issuccse = true;
            });

            showDialog(
                context: context,
                builder: (context) {
                  return CupertinoAlertDialog(
                    title: Text(DemoLocalizations.of(context)
                        .Distributionnetworksuccess),
                    content: SizedBox(
                      height: 30.0,
                      child: Center(
                          child: Text(
                        conmmonResult.message,
                        textAlign: TextAlign.center,
                        style: TextStyle(fontSize: 20),
                      )),
                    ),
                    actions: <Widget>[
                      CupertinoDialogAction(
                        child: Text(DemoLocalizations.of(context).confirm),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  );

                  AlertDialog(
                    title: Text('绑定成功提示'),
                    content: Text(conmmonResult.message),
                    actions: <Widget>[
                      FlatButton(
                        child: Text('确认'),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  );
                });
          } else {
            if (issuccse) {
              return;
            }
            setState(() {
              _msg = conmmonResult.message;
            });
            showToast(conmmonResult.message);
          }
        } else {
          showToast(DemoLocalizations.of(context).Bindingprogress);
          _localTime++;
          if (_localTime > 5) {
            if (issuccse) {
              return;
            }
            showToast(DemoLocalizations.of(context).BindingFailedPleaseCheck);
          } else {
            Future.delayed(Duration(seconds: 2), () {
              bindAt24C16(lanip);
//            print('延时2s执行');
            });
          }
        }
      }, url);
    }
  }

  void myappPair(Function callback, String url) async {
    Dio dio = new Dio(); // 使用默认配置
    // 配置dio实例
    dio.options.baseUrl = url;
    dio.options.connectTimeout = 10000; //5s
    dio.options.receiveTimeout = 8000;
    Response response;
    response = await dio.get("");
    print('response is');
    print(response.data);
    callback(response);
  }
}
